<?php
/*
 * Install OTP validation and key mgmt servers
 * 
 * Make sure you run the schema setup sql script already to set up
 * the DB schema. 
 */

require_once 'config.php';

//// Test DB
//
require_once 'appinclude.php';
require_once 'yubi_lib.php';
//require_once '../wsapi/common.php';

$conn = testDB($baseParams['__DB_HOST__'], $baseParams['__DB_USER__'], 
	$baseParams['__DB_PW__'], $baseParams['__DB_NAME__']);

if (testSchema()) {
	echo "Data schema seems OK, now insert initial data\n";	
}

//// Insert initial data into DB 
//
echo "Insert root client\n";
//INSERT INTO `clients` VALUES 
//(1,1,1,'1970-01-01 00:00:00','your_email@your_email_domain.com',
//'571dm......T983eDqhuOplnHk8=',NULL)
$stmt = 'INSERT INTO clients VALUES (1,1,1,' .
		'NOW(),'.
		mysql_quote($baseParams['__ROOT_EMAIL__']).','.
		mysql_quote(aesEncrypt(genAPIKey())).','.
		mysql_quote('Root client').','.
		'0,0,1'.
		')';
query($stmt);

$devId = substr($otp, 0, 12);
$devId_b64 = modhexToB64($devId);

echo "Insert root client key\n";
//INSERT INTO `yubikeys` VALUES (1,1,1,'2007-10-03 16:11:50',
//'2007-10-22 22:08:18',
//'F/qvmYD9','hU+jIRru','zds......3Ynx/BO5nU0BA==',0,0,0,NULL)
$stmt = 'INSERT INTO yubikeys VALUES (1,1,1,' .
	'NOW(),'.
	'NOW(),'.
	mysql_quote($devId_b64).','. // tok id
	mysql_quote(base64_encode(time())).','. // usr id
	mysql_quote(aesEncrypt($aesParams['__ADM_KEY_SECRET__'])).','. // AES secret
	'0,0,0,'.
	mysql_quote('Root admin key').','.
	mysql_quote('00001001').
	',0)';
query($stmt);

echo "Insert root admin\n";
//'INSERT INTO admin VALUES (1, key_id,'Root Adm Key',
//'OlEMemiArMptNPXxSlG1Nw==','2008-09-03 02:21:34','192.168.1.100',
//'2008-08-07 21:27:51',1,3600)
$stmt = 'INSERT INTO admin (keyid,pin,note,ip,last_access,client,creation) VALUES ('.
	'1,'.
	mysql_quote(aesEncrypt($pin)).','.
	mysql_quote('Root admin').','.
	mysql_quote('127.1.1.0').','.
	'NOW(),'.
	'1,'.
	'NOW())';
query($stmt);

mysql_close($conn);


function testSchema() {
	global $conn;
	$stmt = 'SELECT id FROM clients';
	$r = query($stmt);
	$n = mysql_num_rows($r);
	mysql_free_result($r);
	return $n > 0;
}

function testDB($host, $usr, $pw, $db) {
	$link = mysql_connect($host, $usr, $pw);
	if (!$link) {
		die('Could not connect: ' . mysql_error());
	}
	mysql_select_db($db, $link) or die('Could not select database '.$db);
	echo "\n* Connected to DB successfully\n";
	return $link;
}

function replaceInFile($inFname, $strs, $outFname) {
	$in = fopen($inFname, "r");
	$content = fread($in, filesize($inFname));
	fclose($in);
	foreach (array_keys($strs) as $srch) {
		echo ' Replace ' . $srch . " with\n " . $strs[$srch] . "\n in " . $inFname . "\n";
		$content = str_replace($srch, $strs[$srch], $content);
	}

	$out = fopen($outFname, "w");
	fwrite($out, $content);
	fclose($out);
}

?>
